package com.richinfo.nio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

import com.richinfo.nio.client.handler.NioClientHandler;

/**
 * Nio客户端
 * 
 * Created by WangXJ
 * 2019-07-11 14:34
 */
public class NioClient {

	/**
	 * 启动
	 */
	public void start(String nickName) throws IOException {
		// 1.连接服务器端
		SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8000));
		System.out.println("======== 客户端-启动成功 ========");
		// 2.接收服务器端响应
		// 新开一个线程，专门负责接收服务器端的响应数据
		Selector selector = Selector.open();
		socketChannel.configureBlocking(false);
		socketChannel.register(selector, SelectionKey.OP_READ);
		new Thread(new NioClientHandler(selector)).start();
		
		// 3.向服务器端发送数据
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNextLine()) {
			String request = scanner.nextLine();
			if (request != null && request.length() > 0) {
				socketChannel.write(Charset.forName("UTF-8").encode(nickName + " : " + request)); 
			}
		}
	}

}
